package com.algrithom.linktable;

import com.common.model.ListNode;
import com.util.CommonUtil;

/**
 * 160. 相交链表
 *
 * @author think
 * @since 2020/5/24
 */
public class Solution1 {
    
    public static void main(String[] args){
        ListNode<Integer> listNode1 = CommonUtil.createListNode(new Integer[]{4,1,8,4,5});
        ListNode<Integer> listNode2 = CommonUtil.createListNode(new Integer[]{5,6,1});
        listNode2.getNext().getNext().setNext(listNode1.getNext().getNext());
        ListNode<Integer> result = getIntersectionNode(listNode1,listNode2);
        System.out.println("The intercepter node is: " + result.getVal());
    }
    
    /**
     * 双指针方法
     *
     * @param headA 链表1
     * @param headB 链表2
     * @return 相交节点
     */
    public static ListNode<Integer> getIntersectionNode(ListNode<Integer> headA,ListNode<Integer> headB){
        if (headA == null || headB == null) {
            return null;
        }
        ListNode<Integer> apointer = headA;
        ListNode<Integer> bpointer = headB;
        while (apointer != bpointer) {
            apointer = apointer == null ? headB : apointer.getNext();
            bpointer = bpointer == null ? headA : bpointer.getNext();
        }
        return apointer;
    }
}
